package com.demo.kotlin

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.webkit.WebView
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ProcessUtils
import com.blankj.utilcode.util.ToastUtils
import com.demo.kotlin.network.CommonApiService
import com.demo.kotlin.ui.main.MainActivity
import com.ptt.jituangou.utils.impl.MyActivityLifecycleCallbacks
import com.puhui.lib.network.NetworkManager
import com.puhui.lib.network.interceptors.RequestInterceptor
import com.puhui.lib.utils.ForegroundCallbacks
import com.puhui.lib.utils.reportCaughtException
import com.scwang.smartrefresh.header.MaterialHeader
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import io.reactivex.plugins.RxJavaPlugins

class KotlinApplication : Application() {
    private var isForeground = false //用来判断当前APP是否在运行状态且用户可见

    //用来处理应用自身在后台运行的情况
    @SuppressLint("HandlerLeak")
    private val applicationHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                Exit_App_Handler_Code -> {
                    this.removeMessages(Exit_App_Handler_Code)
                    //由于部分WebView页面可能是由其他进程打开，故如果是由其他进程打开而进入后台的话，则不需要退出应用
                    if (canAutoExitApp) AppUtils.exitApp()
                }
            }
        }
    }

    companion object {
        private const val Exit_App_Handler_Code = 1000 //退出应用的messageWhat
        var isHotLaunchApp: Boolean = false  //是否热启动APP
        var canAutoExitApp = true  //在进入后台一段时间后，是否可以自动退出应用
        private lateinit var instance: KotlinApplication

        @JvmStatic
        fun getInstance(): KotlinApplication {
            return instance
        }
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        initThirdSdk()
        initWebView()
    }

    private fun initThirdSdk() {
        val processName = ProcessUtils.getCurrentProcessName()
        if (BuildConfig.APPLICATION_ID != processName) {
            return
        }

        initLanguage()
        initSmartRefreshLayout()

        Thread(Runnable {
//            GreenDaoUtils.initGreenDao()
            handleRxJavaException()
            closeAndroidPDialog()
            registerActivityLifecycleCallback()
            initNetwork()
        }).start()
    }

    /**
     * 初始化 NetworkManager
     */
    private fun initNetwork() {
        NetworkManager.addInterceptor(RequestInterceptor())
        NetworkManager.addBaseUrl(CommonApiService::class.java, CommonApiService.Base_Url)
    }

    /**
     * 解决问题：Using WebView from more than one process at once with the same data directory is not supported
     */
    private fun initWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName()
            WebView.setDataDirectorySuffix(processName)
        }
    }

    private fun initSmartRefreshLayout() {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context: Context, layout: RefreshLayout ->
            layout.setPrimaryColorsId(R.color.white, R.color.text_color_6) //全局设置主题颜色
            MaterialHeader(context)
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context: Context, layout: RefreshLayout? ->
            val footer = ClassicsFooter(context)
            footer.setAccentColor(ContextCompat.getColor(context, R.color.text_color_c))
            ClassicsFooter.REFRESH_FOOTER_NOTHING = getString(R.string.refresh_footer_nothing)
            footer
        }
    }

    /**
     * 处理RxJava未知异常, 如字段类型不匹配引起的异常
     */
    private fun handleRxJavaException() {
        RxJavaPlugins.setErrorHandler { throwable: Throwable? ->
            if (null != throwable) {
                reportCaughtException(throwable)
                ToastUtils.showShort("系统繁忙，请稍后再试")
            }
        }
    }

    /**
     * 解决androidP 第一次打开程序出现莫名弹窗，不确定P以上是否有该现象，故 >=
     * 弹窗内容“detected problems with api ”
     * 原因是谷歌不允许提供反射去调用非公开的API，当反射调用的时候就会有这个提示
     */
    private fun closeAndroidPDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try {
                val aClass = Class.forName("android.content.pm.PackageParser\$Package")
                val declaredConstructor = aClass.getDeclaredConstructor(String::class.java)
                declaredConstructor.isAccessible = true
            } catch (e: Exception) {
                e.printStackTrace()
            }
            try {
                val cls = Class.forName("android.app.ActivityThread")
                val declaredMethod = cls.getDeclaredMethod("currentActivityThread")
                declaredMethod.isAccessible = true
                val activityThread = declaredMethod.invoke(null)
                val mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown")
                mHiddenApiWarningShown.isAccessible = true
                mHiddenApiWarningShown.setBoolean(activityThread, true)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    // region ActivityLifecycleCallback相关
    /**
     * 监听应用自身是前台运行，还是后台运行
     */
    private fun addForegroundListener() {
        val callbacks: ForegroundCallbacks = ForegroundCallbacks.get(this)
        callbacks.addListener(object : ForegroundCallbacks.Listener {

            override fun onBecameForeground() {
                isForeground = true
                applicationHandler.removeMessages(Exit_App_Handler_Code)
            }

            override fun onBecameBackground() {
                isForeground = false
                //进入后台10分钟结束应用
                applicationHandler.sendEmptyMessageDelayed(Exit_App_Handler_Code, 10 * 60 * 1000.toLong())
            }
        })
    }

    private fun registerActivityLifecycleCallback() {
        addForegroundListener()

        registerActivityLifecycleCallbacks(object : MyActivityLifecycleCallbacks() {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                // 对Application和Activity更新上下文的语言环境
//                LanguageUtilsTwo.applyAppLanguage(activity)
            }

            override fun onActivityResumed(activity: Activity) {
                if (activity is MainActivity) {
                }
            }
        })
    }
    // endregion

    /**
     * 判断当前应用是否在前台
     */
    fun isForeground(): Boolean {
        return isForeground
    }

    private fun initLanguage() {
//        MultiLanguage.init { context -> //返回自己本地保存选择的语言设置
//            LocalManageUtil.getSetLanguageLocale(context)
//        }
//        MultiLanguage.setApplicationLanguage(this)
    }

//
    /**
     * 语言切换
     * 在application 的 attachBaseContext设置当前设置的语言Local
     * 在application 的onConfigurationChanged（改变系统语言时会调用到）设置当前的语言Local
     * 在 Activity 的attachBaseContext设置当前设置的语言Local，所以一般这里是创建BaseActivity来方便统一改变
     * 在 service 的attachBaseContext设置当前设置的语言Local
     */
//    override fun attachBaseContext(base: Context) {
//        //第一次进入app时保存系统选择语言(为了选择随系统语言时使用，如果不保存，切换语言后就拿不到了）
//        LocalManageUtil.saveSystemCurrentLanguage(base)
//        super.attachBaseContext(MultiLanguage.setLocal(base))
//    }
//
//    override fun onConfigurationChanged(newConfig: Configuration) {
//        super.onConfigurationChanged(newConfig)
//        //用户在系统设置页面切换语言时保存系统选择语言(为了选择随系统语言时使用，如果不保存，切换语言后就拿不到了）
//        LocalManageUtil.saveSystemCurrentLanguage(applicationContext, newConfig)
//        MultiLanguage.onConfigurationChanged(applicationContext)
//    }

}